package com.wbao.dianniu.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.AmDataChangeManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.List;


/**
 * 匿名八卦
 *
 * @author yejianjun
 */
public class AnonymousAdapter extends BaseAdapter implements IQuestDelListener {
    private Context mContext;
    List<QaResponse> mList;
    private LayoutInflater mInflater;
    int maxDescripLine = 3;
    private int type;
    private final int TYPE_ANONYMOUS = 1;
    private final int TYPE_PARININ = 2;
    private QuestDelManager manager;
    private int position;

    public AnonymousAdapter(Context ctx, int type) {
        mContext = ctx;
        mInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mList = new ArrayList<QaResponse>();
        this.type = type;
        manager = new QuestDelManager(mContext);
        manager.addQuestDelListener(this);
//		if(TYPE_ANONYMOUS == type){
//
//		}else if(TYPE_PARININ == type){
//
//		}

    }

    /**
     * 清空数据
     */
    public void cleanData() {
        if (null != mList) {
            mList.clear();
        }

    }

    /**
     * 最后一条数据的ID，倒序排列，这条数据最老
     *
     * @return
     */
    public Integer getLastId() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        return mList.get(mList.size() - 1).id;
    }

    /**
     * 第一条数据的ID，倒序排列，这条数据最新
     *
     * @return
     */
    public Integer getFirstId() {
        if (null == mList || 0 == mList.size()) {
            return null;
        }
        return mList.get(0).id;
    }

    /**
     * 向前追加数据
     *
     * @param list
     */
    public void addForwardList(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        mList.addAll(0, list);
    }

    /**
     * 向后追加数据
     *
     * @param list
     */
    public void addBackwardList(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }

        mList.addAll(mList.size(), list);
    }

    public void setData(List<QaResponse> list) {
        if (null == mList) {
            mList = new ArrayList<QaResponse>();
        }
        mList = list;
    }

    public List<QaResponse> getList() {
        return mList;
    }

    @Override
    public int getCount() {
        if (null == mList)
            return 0;
        else
            return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        GridHolder holder = null;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.anonymous_list_item, null);
            holder = new GridHolder();
            holder.forwardTV = (TextView) convertView.findViewById(R.id.include_forward_tv);
            holder.praiseTV = (TextView) convertView.findViewById(R.id.include_praise_tv);
            holder.commentTV = (TextView) convertView.findViewById(R.id.include_answer_tv);
            holder.gridview = (CanDoBlankGridView) convertView.findViewById(R.id.anony_gridview);
            holder.content = (TextView) convertView.findViewById(R.id.anonymous_content);
            holder.deleteTV = (TextView) convertView.findViewById(R.id.include_delete_tv);
            holder.visitorTV = (TextView) convertView.findViewById(R.id.include_visitor_tv);
            convertView.setTag(holder);
        } else {
            holder = (GridHolder) convertView.getTag();
        }
        if (null == mList || mList.size() < position) {
            return convertView;
        }
        if (type == TYPE_ANONYMOUS) {
            holder.deleteTV.setVisibility(View.VISIBLE);
        } else if (type == TYPE_PARININ) {
            holder.deleteTV.setVisibility(View.GONE);
        }

        final QaResponse resp = mList.get(position);
        if (null != resp) {
            holder.content.setText(resp.content);
            //是否点赞
            if (0 == resp.isGood) {
                Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_nor);
                right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                holder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
            } else {
                Drawable right_draw = mContext.getResources().getDrawable(R.drawable.click_praise_icon_sel);
                right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
                holder.praiseTV.setCompoundDrawables(right_draw, null, null, null);
            }
            // 删除按钮
            if (resp.accountId == GlobalContext.getAccountId()) {
                holder.deleteTV.setVisibility(View.VISIBLE);
            } else {
                holder.deleteTV.setVisibility(View.INVISIBLE);
            }
            Utils.showPriseCounts(resp.goodCount, holder.praiseTV);
            Utils.showPriseCounts(resp.answerCount, holder.commentTV);
            Utils.showVisitorCounts(resp.visitorCount, holder.visitorTV);
//			Utils.showPriseCounts(resp.forwardCount, holder.forwardTV);
        }
        holder.deleteTV.setOnClickListener(new DeleteListener(position, resp.id));
        holder.content.setOnClickListener(new DetailListener(resp, position));
        holder.praiseTV.setOnClickListener(new praiseListener(position, resp.isGood, resp.goodCount));
        //分享
        holder.forwardTV.setOnClickListener(new ShareListener(resp));
        holder.commentTV.setOnClickListener(new DetailListener(resp, position));
        if (TextUtils.isEmpty(resp.questImgs)) {
            holder.gridview.setVisibility(View.GONE); // 没有图片资源就隐藏GridView
        } else {
            ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
            holder.gridview.setVisibility(View.VISIBLE);
            //通过图片张数 设置gridview的高度
            double multiple = Math.ceil((float) imageUrls.size() / GlobalContext.NUMCOLUMNS);
            int height = (int) (Utils.dip2px(mContext, 80) * multiple + (multiple - 1) * Utils.dip2px(mContext, 10));
            int width = 0;
            if (multiple >= 1) {
                width = Utils.dip2px(mContext, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS - 1) * Utils.dip2px(mContext, 5);
            } else {
                width = Utils.dip2px(mContext, 80) * imageUrls.size() + (imageUrls.size() - 1) * Utils.dip2px(mContext, 5);
            }
            width = width + Utils.dip2px(mContext, 10);// 加上pendingLeft 10dp
            LayoutParams lp = new LayoutParams(width, height);
            holder.gridview.setLayoutParams(lp);
            holder.gridview.setAdapter(new NoScrollGridAdapter(mContext, imageUrls));
            // 点击回帖九宫格，查看大图
            holder.gridview.setOnItemClickListener(new MyItemClickListener(imageUrls));
            holder.gridview.setOnTouchInvalidPositionListener(new CanDoBlankGridView.OnTouchInvalidPositionListener() {

                @Override
                public boolean onTouchInvalidPosition(int motionEvent) {
                /*
				 * 当返回false的时候代表交由父级控件处理，当return
				 * true的时候表示你已经处理了该事件并不让该事件再往上传递
				 * 。为了出发listview的item点击就得返回false了
				 */
                    return false;
                }
            });

        }
        return convertView;
    }

    class DeleteListener implements OnClickListener {

        private int index;
        private int questId;

        public DeleteListener(int position, int questId) {
            this.index = position;
            this.questId = questId;
        }

        @Override
        public void onClick(View v) {
            //
            CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
            builder.setTitle("确认删除该条匿名吗？");
            builder.setPositiveButton(mContext.getResources().getString(R.string.confirm),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            position = index;
                            if (null != manager)
                                manager.deleteQuest(GlobalContext.getAccountId(), questId);
                        }
                    });
            builder.setNegativeButton(mContext.getResources().getString(R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
        }
    }

    /**
     * 分享
     */
    private class ShareListener implements OnClickListener {
        private QaResponse resp;

        public ShareListener(QaResponse resp) {
            this.resp = resp;
        }

        @Override
        public void onClick(View v) {
            String imageUrl = null;
            if (TextUtils.isEmpty(resp.questImgs)) {
                imageUrl = GlobalContext.cdndownUrl + "logo.png";
            } else {
                ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                imageUrl = imageUrls.get(0);
            }
            ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
            shareSDKManager.showShare(mContext, resp.content, 7, imageUrl, resp.id);
        }

    }

    /**
     * 点赞
     */
    class praiseListener implements OnClickListener {

        private int isGood;
        private int position;
        private int goodCount;

        public praiseListener(int position, int isGood, int goodCount) {
            this.isGood = isGood;
            this.position = position;
            this.goodCount = goodCount;
        }

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.include_praise_tv) {
                if (isGood == 0) {
                    isGood = 1;
                    goodCount++;
                } else {
                    isGood = 0;
                    goodCount--;
                }
                AmDataChangeManager manager = AmDataChangeManager.getInstance();
                manager.priseNotify(mList.get(position).id, isGood, goodCount);
                goodclick(mList.get(position).id);
            }
        }

    }

    private void goodclick(int questId) {
        QuestGoodManager manager = new QuestGoodManager(mContext);
        manager.good(GlobalContext.getAccountId(), questId);
    }

    /**
     * 点击查看详情
     */
    private class DetailListener implements OnClickListener {
        private QaResponse resp;
        private int pos;

        public DetailListener(QaResponse resp, int position) {
            this.resp = resp;
            pos = position;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.anonymous_content:
                case R.id.include_answer_tv:
                    Utils.intoAmDetailActivity(mContext, resp);
                    break;

                default:
                    break;
            }
        }

    }

    public class GridHolder {
        /** 展开 */
//		public Button openBtn;
        /**
         * 内容
         */
        public TextView content;
        /**
         * 转发数
         */
        public TextView forwardTV;
        /**
         * 点赞数
         */
        public TextView praiseTV;
        /**
         * 回复数
         */
        public TextView commentTV;
        /**
         * 图片显示
         */
        public CanDoBlankGridView gridview;
        /**
         * 删除按钮
         */
        public TextView deleteTV;
        /**
         * 浏览
         */
        public TextView visitorTV;
    }

//	@Override
//	public void countsChanged(int questId, int goodCounts, int answerCounts,int isGood) {
//		if (null != mList) {
//			for (int i = 0; i < mList.size(); i++) {
//				if (mList.get(i).id == questId) {
//					mList.get(i).goodCount = goodCounts;
//					mList.get(i).answerCount = answerCounts;
//					mList.get(i).isGood = isGood;
//					notifyDataSetChanged();
//					break;
//				}
//			}
//		}
//	}

    public void addOneQuestData(QaResponse addData) {
        if (null != mList) {
            mList.add(0, addData);
            notifyDataSetChanged();
        }
    }

    class MyItemClickListener implements OnItemClickListener {

        private ArrayList<String> url;

        public MyItemClickListener(ArrayList<String> url) {
            this.url = url;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // TODO Auto-generated method stub
            //弹出图片查看按钮
            imageBrower(position, url);
        }

    }

    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(mContext, position, urls2);
    }

    public void removeOneData(int id) {
        // TODO Auto-generated method stub
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == id) {
                mList.remove(i);
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void priseNotify(int questId, int isGood, int goodCounts) {
        // TODO Auto-generated method stub
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).isGood = isGood;
                mList.get(i).goodCount = goodCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void replyNotify(int questId, int answerCounts) {
        // TODO Auto-generated method stub
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).answerCount = answerCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    public void updateVisitor(int questId, int visitorCounts) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).id == questId) {
                mList.get(i).visitorCount = visitorCounts;
                notifyDataSetChanged();
                break;
            }
        }
    }

    @Override
    public void onQuestDelFailure(int errorCode, String errorMsg) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onQuestDelSuccess() {
        // TODO Auto-generated method stub
        // 通知其它界面数据改变
        AmDataChangeManager manager = AmDataChangeManager.getInstance();
        manager.notifyRemove(mList.get(position).id);
    }

}
